<?php

namespace App\Services\MakeProductOrder;

use App\Models\Order;
use App\Models\Address;
use App\Models\ProductSku;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class MakeProductOrderRequest extends FormRequest
{
	protected ?Address $address = null;

	public function rules(): array
	{
		/*$todayUnpaidOrders = $this->user()->todayUnpaidOrdersCount();
		if ($todayUnpaidOrders >= 10) {
			$this->user()->update(['is_locked' => true]);
			fail('账号操作异常，请联系客服');
		}*/

		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}

		return [
			'address_id' => ['required', $this->address()],
			'sku_id' => [
				'required_without:attr_value_index',
				'integer', $this->sku()
			],
			'attr_value_index' => $this->attrValueIndex(),
			'amount' => 'required|integer|min:1',
		];
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			if (!$this->address) {
				return $fail('地址不存在');
			}/* elseif (!Order::isAddressSupported($this->address)) {
				return $fail('地址不在配送范围');
			}*/
			return true;
		};
	}

	public function sku()
	{
		return function ($attribute, $value, $fail) {
			if (!$sku = ProductSku::find($value)) {
				return $fail('此商品不存在');
			} elseif (!$sku->product->is_sale) {
				return $fail('此商品未上架');
			} elseif ($sku->stock === 0) {
				return $fail('此商品已售完');
			} elseif ($sku->product->is_hongkong_direct
				or $sku->product->is_overseas_direct) {
				if (!$this->address->id_code) {
					return $fail('海外直邮商品提供收件人证件号码');
				}
			}
			preg_match('/items\.(\d+)\.sku_id/', $attribute, $m);

			$amount = request()->amount;
			if ($amount > 0 and $amount > $sku->stock) {
				return $fail('此商品库存不足');
			}
			return true;
		};
	}

	protected function attrValueIndex()
	{
		return [
			'required_without:sku_id',
			'string',
			function ($attribute, $value, $fail) {
				if (!$sku = sku_from_attr($value)) {
					return $fail('此商品不存在');
				} elseif (!$sku->product->is_sale) {
					return $fail('此商品未上架');
				} elseif ($sku->stock === 0) {
					return $fail('此商品已售完');
				}
				preg_match('/items\.(\d+)\.attr_value_index/', $attribute, $m);
				
				$amount = request()->amount;
				if ($amount > 0 and $amount > $sku->stock) {
					return $fail('此商品库存不足');
				}
				return true;
			}
		];
	}

	public function getAddress(): Address
	{
		return $this->address;
	}

	public function items()
	{
		$item['items'] = [
			'sku_id'=>request()->sku_id,
			'attr_value_index' => request()->attr_value_index,
			'amount'=> request()->amount,
		];
		return $item;


	}
}
